package com.whnk.pm.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.whnk.common.support.Convert;
import com.whnk.common.utils.StringUtils;
import com.whnk.pm.domain.EduInfo;
import com.whnk.pm.dto.Duration;
import com.whnk.pm.mapper.EduInfoMapper;
import com.whnk.pm.service.IEduInfoService;
import com.whnk.pm.util.DateUtil;

/**
 * 教育经历 服务层实现
 * 
 * @author whwhnk
 * @date 2019-07-05
 */
@Service
public class EduInfoServiceImpl implements IEduInfoService 
{
	@Autowired
	private EduInfoMapper eduInfoMapper;

	/**
     * 查询教育经历信息
     * 
     * @param empSn 教育经历ID
     * @return 教育经历信息
     */
    @Override
	public EduInfo selectEduInfoById(Integer empSn)
	{
	    return eduInfoMapper.selectEduInfoById(empSn);
	}
	
	/**
     * 查询教育经历列表
     * 
     * @param eduInfo 教育经历信息
     * @return 教育经历集合
     */
	@Override
	public List<EduInfo> selectEduInfoList(EduInfo eduInfo)
	{
		List<EduInfo> eduInfoList = eduInfoMapper.selectEduInfoList(eduInfo);
		eduInfoList.sort(Comparator.comparing((k1) -> (
				(k1.getEmpGradDt() == null ? new Date(): k1.getEmpGradDt())
		)));
	    return eduInfoList;
	}
	
    /**
     * 新增教育经历
     * 
     * @param eduInfo 教育经历信息
     * @return 结果
     */
	@Override
	public int insertEduInfo(EduInfo eduInfo)
	{
	    return eduInfoMapper.insertEduInfo(eduInfo);
	}
	
	/**
     * 修改教育经历
     * 
     * @param eduInfo 教育经历信息
     * @return 结果
     */
	@Override
	public int updateEduInfo(EduInfo eduInfo)
	{
		int result = eduInfoMapper.insertEduInfo(eduInfo);
	    return result;
	}

	/**
     * 删除教育经历对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteEduInfoByIds(String ids)
	{
		return eduInfoMapper.deleteEduInfoByIds(Convert.toStrArray(ids));
	}
	
	/**
	 * 验证时间 不可重复
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String checkDate(String stDt, String endDt, String empid, String operationType, String id) throws ParseException {
		DateFormat dateTimeFormatter = new SimpleDateFormat("yyyy-MM-dd");
		Date startDate = dateTimeFormatter.parse(stDt);
		Date endDate = dateTimeFormatter.parse(endDt);
		if (endDate.before(startDate)) {
			throw new RuntimeException();
		}
		if (StringUtils.equalsIgnoreCase("edit", operationType)) {
			eduInfoMapper.deleteEduInfoById(Integer.valueOf(id));
		}

		EduInfo edu = new EduInfo();
		edu.setEmpId(empid);
		List<Duration> list =
				eduInfoMapper.selectEduInfoList(edu).stream().map(k ->
						new Duration(k.getEmpEnroDt(), k.getEmpGradDt())
				).collect(Collectors.toList());
		return DateUtil.durationOverlap(startDate, endDate, list, operationType);
	}
	
}
